package club.caihappy.Servlet;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Created by DELL on 2021/10/20
 **/
@WebServlet(value = "/async", asyncSupported = true)
public class HelloAsyncServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("主线程开始..." + Thread.currentThread()+"==>"+System.currentTimeMillis());

        AsyncContext asyncContext = req.startAsync();
        asyncContext.start(new Runnable() {
            @Override
            public void run() {
                System.out.println("副线程开始..." + Thread.currentThread()+"==>"+System.currentTimeMillis());
                sayHello();
                asyncContext.complete();
                //第四步:获取响应
                ServletResponse response = asyncContext.getResponse();

                try {
                    response.getWriter().write("hello async...");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("副线程结束..." + Thread.currentThread()+"==>"+System.currentTimeMillis());
            }
        });
        System.out.println("主线程结束..." + Thread.currentThread()+"==>"+System.currentTimeMillis());
    }

    public void sayHello() {
        try {
            System.out.println(Thread.currentThread() + " processing...");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
